package cn.javaxc.mvcwork.util.io;
import cn.javaxc.mvcwork.util.common.StringUtils;
import java.io.*;
import java.util.zip.*;



public class ZipUtils {

  
  public static void addTextEntry(ZipOutputStream zip, String fileName, String data) throws ZipException, IOException {
    int bytesRead;
    StringReader file = new StringReader(data);
    ZipEntry entry = new ZipEntry(fileName);
    zip.putNextEntry(entry);
    while ((bytesRead = file.read()) != -1) {
      zip.write(bytesRead);
    }
  }


  
  public static void extract(File zipFile, String destination) throws IOException {
    ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile));
    ZipEntry entry = null;
    byte[] buffer = new byte[1024];
    while ((entry = zip.getNextEntry()) != null) {
      if (entry.isDirectory()) {
        File directory = new File(destination + entry.getName());
        directory.mkdirs();
      } else {
        FileOutputStream file = new FileOutputStream(
            destination + entry.getName());
        int count;
        while ((count = zip.read(buffer)) != -1) {
          file.write(buffer, 0, count);
        }
        file.close();
      }
    }
    zip.close();
  }


  
  public static void extract(ZipFile zipFile, String entry, String destination) throws IOException {
    ZipEntry zipEntry = zipFile.getEntry(entry);
    if (zipEntry == null) {
      zipEntry = zipFile.getEntry(entry.replace( "/", "\\"));
    }
    if (zipEntry == null) {
      zipEntry = zipFile.getEntry(entry.replace( "\\", "/"));
    }
    InputStream inputStream = zipFile.getInputStream(zipEntry);
    byte[] buffer = new byte[inputStream.available()];
    if (zipEntry != null) {
      if (zipEntry.isDirectory()) {
        //do nothing
      } else {
        int offset = 0;
        int numRead = 0;
        while (offset < buffer.length
            && (numRead = inputStream.read(buffer, offset, buffer.length - offset)) >= 0) {
          offset += numRead;
        }
        FileUtils.copyBytesToFile(buffer, new File(destination), true);
      }
    }
    inputStream.close();
  }


  
  public static void compress(String inputFile, File zipFile) throws IOException {
    ZipUtils.compress(inputFile, zipFile, inputFile);
  }
  
  
  public static void compress(String inputFile, File zipFile, String entryName) throws IOException {
    byte[] buffer = new byte[1024];

    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile));
    FileInputStream fin = new FileInputStream(inputFile);

    zip.putNextEntry(new ZipEntry(entryName));

    int len = -1;
    while ((len = fin.read(buffer)) > 0) {
      zip.write(buffer, 0, len);
    }

    zip.closeEntry();
    fin.close();
    zip.close();
  }
}
